<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\Project;
use think\facade\View;

class ProjectController extends BaseController
{
    /**
     * 项目列表
     */
    public function index(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $status = $request->param('status');
        $category = $request->param('category');
        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        $query = Project::where('user_id', $user->id);

        if (!empty($status)) {
            $query->where('status', $status);
        }
        if (!empty($category)) {
            $query->where('category', $category);
        }

        $projects = $query->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        // 格式化项目数据，添加剩余天数
        $formattedProjects = array_map(function($project) {
            $data = $project->toArray();
            $data['remaining_days'] = $project->getRemainingDays();
            $data['status_text'] = Project::$statusMap[$project->status] ?? '未知状态';
            $data['progress'] = $project->getProgress();
            $data['is_overdue'] = $project->isOverdue();
            return $data;
        }, $projects->items());

        return json([
            'status' => 200,
            'data' => [
                'total' => $projects->total(),
                'current_page' => $projects->currentPage(),
                'last_page' => $projects->lastPage(),
                'projects' => $formattedProjects
            ]
        ]);
    }

    /**
     * 创建项目
     */
    public function create(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        $start_date = date('Y-m-d');
        if(!empty($data['start_date_date'])){
            $start_date = $data['start_date_date'];
        }
        
        // 只验证项目名称
        if (empty($data['name'])) {
            return json(['status' => 400, 'message' => '请填写项目名称']);
        }

        try {
            $project = new Project;
            $project->user_id = $user->id;
            $project->name = $data['name'];
            $project->goal = $data['goal'] ?? '';  // 目标可选
            $project->description = $data['description'] ?? '';
            $project->category = $data['category'] ?? null;
            // 开始时间默认为当前时间
            $project->start_date = $start_date;
            // 计划时长默认为0
            $project->duration = $data['duration'] ?? 0;
            $project->status = Project::STATUS_ONGOING;
            $project->save();

            // 记录操作日志
            UserController::logOperation($user->id, 'create_project', "创建项目：{$data['name']}", $request);

            return json([
                'status' => 200,
                'message' => '项目创建成功',
                'data' => $project
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新项目
     */
    public function update(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $projectId = $request->param('id') ?? $request->post('id');
        $data = $request->post();
        // $projectId = $data['id'];
        // return json($projectId);

        $project = Project::where('id', $projectId)
            ->where('user_id', $user->id)
            ->find();

        if (!$project) {
            return json(['status' => 404, 'message' => '项目不存在或无权限']);
        }

        try {
            $project->save($data);

            UserController::logOperation($user->id, 'update_project', "更新项目：{$project->name}", $request);

            return json(['status' => 200, 'message' => '更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新项目状态
     */
    public function updateStatus(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $projectId = $request->param('id') ?? $request->post('id');
        $status = $request->param('status') ?? $request->post('status') ;

        if (!in_array($status, [
            Project::STATUS_ONGOING,
            Project::STATUS_COMPLETED,
            Project::STATUS_PAUSED
        ])) {
            return json(['status' => 400, 'message' => '无效的状态值']);
        }

        $project = Project::where('id', $projectId)
            ->where('user_id', $user->id)
            ->find();

        if (!$project) {
            return json(['status' => 404, 'message' => '项目不存在或无权限']);
        }

        try {
            $project->status = $status;
            $project->save();

            $statusText = Project::$statusMap[$status];
            UserController::logOperation(
                $user->id, 
                'update_project_status', 
                "更新项目状态：{$project->name} -> {$statusText}", 
                $request
            );

            return json(['status' => 200, 'message' => '状态更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除项目
     */
    public function delete(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $projectId = $request->param('id') ?? $request->post('id');

        $project = Project::where('id', $projectId)
            ->where('user_id', $user->id)
            ->find();

        if (!$project) {
            return json(['status' => 404, 'message' => '项目不存在或无权限']);
        }

        try {
            $project->delete();

            UserController::logOperation($user->id, 'delete_project', "删除项目：{$project->name}", $request);

            return json(['status' => 200, 'message' => '删除成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取项目详情
     */
    public function detail(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $projectId = $request->param('id');
        if (empty($projectId)) {
            return json(['status' => 400, 'message' => '项目ID不能为空']);
        }

        try {
            // 获取项目信息
            $project = Project::where('id', $projectId)
                ->where('user_id', $user->id)
                ->find();

            if (!$project) {
                return json(['status' => 404, 'message' => '项目不存在']);
            }

            // 获取关联的提醒数量
            $reminderCount = \app\model\Reminder::where('project_id', $projectId)
                ->where('is_disabled', 0)
                ->count();

            // 获取关联的笔记数量
            $noteCount = \app\model\Note::where('id', $projectId)
                ->count();

            // 格式化项目数据
            $data = [
                'id' => $project->id,
                'name' => $project->name,
                'goal' => $project->goal,
                'description' => $project->description,
                'category' => $project->category,
                'status' => $project->status,
                'status_text' => $this->getStatusText($project->status),
                'start_date' => $project->start_date,
                'plan_end_date' => $project->plan_end_date,
                'duration' => $project->getDuration(),
                'remaining_days' => $project->getRemainingDays(),
                'progress' => $project->getProgress(),
                'is_overdue' => $project->isOverdue(),
                'created_at' => date('Y-m-d H:i:s', $project->created_at),
                'updated_at' => date('Y-m-d H:i:s', $project->updated_at),
                'statistics' => [
                    'reminder_count' => $reminderCount,
                    'note_count' => $noteCount
                ]
            ];

            // 记录操作日志
            UserController::logOperation($user->id, 'view_project', "查看项目：{$project->name}", $request);

            return json([
                'status' => 200,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('获取项目详情失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取项目详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取项目状态文本
     */
    private function getStatusText($status)
    {
        $statusMap = [
            Project::STATUS_ONGOING => '进行中',
            Project::STATUS_COMPLETED => '已完成',
            Project::STATUS_PAUSED => '已暂停'
        ];
        return $statusMap[$status] ?? '未知状态';
    }
} 